package MianCalPak;


import java.io.IOException;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.DBProvider;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String login = (String)request.getSession().getAttribute("username");
		
		//logout
		if(login != null)
		{
			request.getSession().removeAttribute("username");
			request.getSession().invalidate();
			response.sendRedirect("");
			return;
		}
			
		String user = request.getParameter("username");
		String pass = request.getParameter("password");	
		
		//Check input
		if (null == pass || null == user || pass.length() > 8 || user.length() > 8){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
			
		}
	
		try {	
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			
			ResultSet res = (new DBProvider(p)).userDetails(user); 
			
			boolean resultFailed = (!res.next() || !res.getString("password").equals(pass));
	
			if (!resultFailed){
				request.getSession().setAttribute("username", user); 
				String admin = res.getBoolean("administrator") ? "true" : "false";
				request.getSession().setAttribute("administrator",admin);
				} 
			
			else {
				request.getSession().setAttribute("LastResultFailed", "true");
			}
			response.sendRedirect("");
		
		}
		
		catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
	}
		
}

